package com.xpp.yanpicturebackend.api.imagesearch.sub;

import com.xpp.yanpicturebackend.exception.BusinessException;
import com.xpp.yanpicturebackend.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 获取图片列表接口的api
 */
@Slf4j
public class GetImageFirstUrlApi {
    /**
     * 获取图片列表接口
     *
     * @param searchResultUrl
     * @return
     */
    public static String getImageFirstUrl(String searchResultUrl) {
        try {
            // 1. 使用 Jsoup 连接并获取 HTML 文档
            Document doc = Jsoup.connect(searchResultUrl)
                    .timeout(5000) // 超时时间 10 秒
                    .get();

            // 2. 获取所有的 <script> 标签
            for (Element script : doc.getElementsByTag("script")) {
                String scriptContent = script.html(); // 获取脚本内容

                // 3. 使用正则表达式匹配 "firstUrl" 的值
                // 匹配类似: "firstUrl":"https://xxxxx..."
                Pattern pattern = Pattern.compile("\"firstUrl\"\\s*:\\s*\"([^\"]+)\"");
                Matcher matcher = pattern.matcher(scriptContent);

                if (matcher.find()) {
                    String firstUrl = matcher.group(1); // 提取匹配到的 URL
                    // 转义
                    firstUrl = firstUrl.replace("\\/", "/");
                    return firstUrl; // 找到后就退出
                }
            }
            log.error("未找到 firstUrl 字段。");
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未找到 URL。");
        } catch (IOException e) {
            log.error("连接或解析网页时出错: " + e.getMessage());
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "搜索失败");
        }
    }

    public static void main(String[] args) {
        String url = "https://graph.baidu.com/s?card_key=&entrance=GENERAL&extUiData[isLogoShow]=1&f=all&isLogoShow=1&session_id=13048869092494586509&sign=12690e97cd54acd88139901749526643&tpl_from=pc";
        String firstUrl = getImageFirstUrl(url);
        System.out.println(firstUrl);
    }
}
